/**
 * 根据模板`a.b+c=&{a.b + c}&` 的 特别标记--( &{a.b+c}& )  进行解析 其中的 表达式 {a{b:3},c:4} 返回 整合后的 字符串
 * @param {String} modelStr 模板 字符串
 * @param {Map} keyV
 */
function evalString(modelStr, keyV) {
  let reKey = /&\{(.*?)\}&/g;

  let spliceCode = ' ';

  let nextExp = modelStr.matchAll(reKey);

  let modelArr = modelStr.split('');

  let ExpKey = { data: [] };

  //偏移 大小
  let dynamicIndex = 0;

  for (let a = nextExp.next(); !a.done; a = nextExp.next()) {
    let keyPice = a['value'][0];

    // 起始位置
    let defaultI = a['value']['index'];

    //填充 文本
    let fillInfo;

    if (ExpKey.data.indexOf(keyPice) == -1) {
      ExpKey.data.push(keyPice);

      fillInfo = EvalStr(a['value'][1]);
      ExpKey[keyPice] = fillInfo;
    } else {
      fillInfo = ExpKey[keyPice];
    }
    modelArr.splice(defaultI + dynamicIndex, a['value'][0].length, ...fillInfo);

    dynamicIndex += fillInfo.length - a['value'][0].length;
  }

  function EvalStr(str) {
    let keyinfo = str.split(spliceCode);
    let key;

    let StringCode = false;

    for (let i = 0; i < keyinfo.length; i++) {
      key = keyinfo[i];
      // 去除空字符串
      if (key == '') {
        keyinfo.splice(i--, 1);
        continue;
      }
      //   字符串 标识符
      if (key == "'") {
        StringCode = !StringCode;
        continue;
      }
      if (StringCode) {
        continue;
      }
      //   纯数字
      if (/^\d*?$/.test(key)) {
        keyinfo.splice(i, 1, Number(key));
        continue;
      }
      //   特殊运算符号 保留字符
      if (
        [
          '+',
          '-',
          '*',
          '/',
          '\\',
          '!',
          '(',
          ')',
          '&',
          '&&',
          '|',
          '||',
          '?',
          ':',
        ].indexOf(key) > -1
      ) {
        continue;
      }

      // 包含位置变量
      if (getKeyValue(keyV, key) == undefined) {
        console.log('sorry we lose some info "' + key + '" : no value !');
        return str;
      }

      keyinfo[i] = getKeyValue(keyV, key);
    }
    return eval(keyinfo.join(' ')).toString().split('');
  }
  //   let cg = modelArr.join('');
  //   console.log(cg);
  //   return cg;
  return modelArr.join('');
}

function getKeyValue(obj, key) {
  let keySourceA = key.split('.');
  //   console.log(keySourceA);
  let ret = obj;
  for (let i = 0; i < keySourceA.length; i++) {
    ret = ret[keySourceA[i]];
    // console.log(ret);
  }
  return ret;
}

export { evalString };
